package com.stylefeng.guns.modular.qinhe.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.stylefeng.guns.GunsApplication;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.base.tips.ErrorTip;
import com.stylefeng.guns.core.base.tips.SuccessTip;
import com.stylefeng.guns.core.node.ZTreeNode;
import com.stylefeng.guns.core.util.Hash;
import com.stylefeng.guns.modular.qinhe.service.ISuCategoryService;
import com.stylefeng.guns.modular.qinhe.service.ISuModelService;
import com.stylefeng.guns.modular.system.model.SuCategory;
import com.stylefeng.guns.modular.system.model.SuModel;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import javax.xml.bind.DatatypeConverter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("/am")
public class AMController extends BaseController {

  @Autowired
  private ISuCategoryService suCategoryService;
  @Autowired
  private ISuModelService suModelService;

  @RequestMapping(value = {"/category/{type}", "/category"})
  @ResponseBody
  public List<ZTreeNode> tree(@PathVariable(required = false) Integer type) {
    List<ZTreeNode> tree = this.suCategoryService.tree(type);
    //tree.add(ZTreeNode.createParent());
    return tree;
  }

  @RequestMapping(value = "/exists/{uploader}")
  @ResponseBody
  public Object existsUploader(@PathVariable String uploader) {
    EntityWrapper<SuModel> wrapper = new EntityWrapper<>();
    wrapper.eq("uploader", uploader);
    int i = suModelService.selectCount(wrapper);
    if (i > 0) {
      return SUCCESS_TIP;
    } else {
      return new ErrorTip(400, "");
    }
  }

  @RequestMapping(value = {"/assets/{bigType}"})
  @ResponseBody
  public Object assets(@PathVariable Integer bigType) {
    switch (bigType) {
      default:
        return fetchModelAssets(bigType);
    }

  }

  private Object fetchModelAssets(Integer bigType) {
    Integer currentPage = getPara("page", 1);
    Integer size = getPara("size", 24);
    Integer isRoot = getPara("root", 0);
    Long category = getPara("category", -1L);

    String modelType = getPara("modelType");
    EntityWrapper<SuModel> wrapper = new EntityWrapper<>();
    String uploader = getPara("uploader");
    if (StringUtils.isNotBlank(uploader)) {
      wrapper.eq("uploader", uploader);
    } else {
      // 1 su模型  2:3d模型 3:FBX模型 4:UE4模型  5 vray材质 6 skm材质 7 ies  8 脚本 9 贴图
      switch (bigType) {
        case 1:
          wrapper.lt("type", 5); // <5的是模型类资源
          break;
        case 2: //ies
          wrapper.eq("type", 7);
          break;
        default:
          wrapper.eq("type",bigType);
      }
      // category==-1 代表不过滤模型分类
      if (category != -1) {
        if (isRoot == 1) {
          List<SuCategory> subCategories = suCategoryService
              .selectList(new EntityWrapper<SuCategory>().eq("pid", category));
          Long[] cids = new Long[subCategories.size() + 1];
          for (int i = 0; i < subCategories.size(); i++) {
            cids[i] = subCategories.get(i).getId();
          }
          cids[subCategories.size()] = category;
          wrapper.in("category", StringUtils.join(cids, ","));
        } else {
          wrapper.eq("category", category);
        }
      }
      // 过滤 su max fbx ue4
      if (StringUtils.isNotBlank(modelType)) {
        wrapper.in("type", modelType);
      }
    }
    wrapper.eq("deleted", 0);
    //wrapper.eq("type", 1);
    wrapper.orderBy("downloads", false);
    wrapper.orderBy("createtime", false);
    return suModelService.selectPage(new Page<>(currentPage, size), wrapper);
  }

  @PostMapping("/upload/model")
  @ResponseBody
  public Object uploadModel(@RequestPart("file") MultipartFile zipFile,
      @RequestPart("thumb") MultipartFile thumbFile) throws IOException {
    File jarFolder = new ApplicationHome(GunsApplication.class).getDir();
    File modelFolder = new File(
        jarFolder + "/models/");
    modelFolder.mkdirs();
    Long newFilename = System.currentTimeMillis();
    String fileext = getPara("fileext").toLowerCase();
    String thumbext = getPara("thumbext").toLowerCase();
    zipFile.transferTo(new File(modelFolder, newFilename + "." + fileext));
    thumbFile.transferTo(new File(modelFolder, newFilename + "." + thumbext));
    SuModel model = new SuModel();
    model.setFilename(newFilename.toString());
    model.setModelname(getPara("modelname"));
    model.setCategory(getPara("category", -1L));
    model.setType(getPara("type", 1));
    model.setFileext(fileext);
    model.setThumbext(thumbext);
    model.setFilesize(new File(modelFolder, newFilename + "." + fileext).length());
    model.setChecksum(DatatypeConverter
        .printHexBinary(Hash.SHA256.checksum(new File(modelFolder, newFilename + "." + fileext)))
        .toLowerCase());
    model.setCreatetime(new Date());
    model.setUploader(getPara("uploader", "AM"));
    suModelService.insert(model);

    return new SuccessTip();
  }


}
